package app

import (
	"github.com/gin-gonic/gin"
	"github.com/gogf/gf/v2/util/guid"
	"path"
	"wx_build/core/msg"
	"wx_build/service"
)

type WxAppletApi struct {
}

func (WxAppletApi) Add(g *gin.Context) {
	var dataService service.WxAppletService
	err := g.ShouldBindJSON(&dataService)
	if err != nil {
		msg.Error(g, err.Error(), err)
		return
	}
	if dataService.Appid == "" {
		msg.Error(g, "小程序的appid不能为空", nil)
		return
	}
	if dataService.PrivateKeyPath == "" {
		msg.Error(g, "小程序的秘钥路径不能为空", nil)
	}
	if dataService.Name == "" {
		msg.Error(g, "小程序的名称不能为空", nil)
	}
	dataService.Add(g)
	return
}
func (WxAppletApi) Update(g *gin.Context) {
	var dataService service.WxAppletService
	err := g.ShouldBindJSON(&dataService)
	if err != nil {
		msg.Error(g, err.Error(), err)
		return
	}
	if dataService.Appid == "" {
		msg.Error(g, "小程序的appid不能为空", nil)
		return
	}
	dataService.Update(g)
	return
}
func (WxAppletApi) List(g *gin.Context) {
	var dataService service.WxAppletService
	err := g.ShouldBindJSON(&dataService)
	if err != nil {
		msg.Error(g, err.Error(), err)
		return
	}
	if dataService.Page == 0 {
		dataService.Page = 1
	}
	if dataService.Size == 0 {
		dataService.Size = 10
	}
	dataService.List(g)
	return

}
func (WxAppletApi) Delete(g *gin.Context) {
	var dataService service.WxAppletService
	err := g.ShouldBindJSON(&dataService)
	if err != nil {
		msg.Error(g, err.Error(), err)
		return
	}
	if dataService.Appid == "" {
		msg.Error(g, "小程序的appid不能为空", nil)
		return
	}
	dataService.Delete(g)
	return
}
func (WxAppletApi) QueryAll(g *gin.Context) {
	var dataService service.WxAppletService
	dataService.QueryAll(g)
	return
}

// UploadFile 上传文件
func (WxAppletApi) UploadFile(g *gin.Context) {
	file, err := g.FormFile("file")
	if err != nil {
		msg.Error(g, "文件不存在", err)
		return
	}
	ext := path.Ext(file.Filename)
	if ext != ".key" {
		msg.Error(g, "只能上传.key的文件", nil)
		return
	}
	name := guid.S()
	err = g.SaveUploadedFile(file, "./wx_app_key/"+name+ext)
	if err != nil {
		msg.Error(g, "上传文件错误", err)
		return
	}
	res := make(map[string]interface{})
	res["url"] = "/wx_app_key/" + name + ext
	msg.Success(g, "上传成功", res)
}
